package com.example.blogdemo.repository;

import com.example.blogdemo.entity.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @Author Anita
 * @Date 2017/12/13 16:19
 */
public interface ArticleRepository extends JpaRepository<Article,Integer>{


    Article findById(Integer id);

    Page<Article> findAll(Pageable pageable);

    Page<Article> findByCategory(String category,Pageable pageable);

    @Query(value = "select count(id) from article where category=:category",nativeQuery = true)
    Integer findArticleCountByCategory(@Param("category")String category);

    @Query(value = "select count(id) from article",nativeQuery = true)
    Integer findArticleCount();


    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "update article a set a.comment_count =?1 where a.id = ?2",nativeQuery = true)
    public void updateCommentCountByQuestionId(Integer commentCount, Integer questionId);


    @Transactional
    @Modifying
    @Query(value = "delete from article where id = :id",nativeQuery = true)
    public void deleteById(@Param("id") Integer id);

    Page<Article> findByUserId(Integer userId,Pageable pageable);

    List<Article> findByUserId(Integer userId);

    List<Article> findByCategoryAndUserId(String category,Integer userId);

    Page<Article> findByCategoryAndUserId(String category,Integer userId,Pageable pageable);
}
